import time
import json
import uuid
from enum import Enum

# 设备状态


class DeviceStatus(Enum):
    STOP = 'STOP'
    RUNNING = 'RUNNING'
    OFFLINE = 'OFFLINE'


def json_default(obj):
    if isinstance(obj, Enum):
        return obj.value
    return {
        'device_id': obj.device_id,
        'status': obj.status,
        'cmd_id': obj.cmd_id,
        'timestamp': obj.timestamp,
        'payload': obj.payload,
        'action': obj.action
    }


class ProtocolPayload:

    def __init__(self, device_id: str, payload=None, timestamp=None, status=None, action=None, cmd_id=None):
        self.device_id = device_id
        self.payload = payload;
        if timestamp is None:
            timestamp = int(round(time.time() * 1000))
        self.timestamp = timestamp

        if status is None:
            self.status = DeviceStatus.OFFLINE
        self.status = status

        self.action = action

        if cmd_id is None:
            cmd_id = str(uuid.uuid4())
        self.cmd_id = cmd_id

    def update_device_status(self, status: DeviceStatus):
        self.status = status

    def to_json(self):
        return json.dumps(self, default=json_default)

    @staticmethod
    def parse_object(obj_dict: dict):
        return ProtocolPayload(obj_dict['device_id'],
                               obj_dict.get('payload'),
                               obj_dict.get('timestamp'),
                               obj_dict.get('status'),
                               obj_dict.get('action'),
                               obj_dict.get('cmd_id'))
